﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao.PlcDao;
using DeHeng_Mes.Model.BossModel;
using DeHeng_Mes.Utils;
using S7.Net;
using System;
using System.CodeDom.Compiler;

namespace DeHeng_Mes.Service.Plc
{
    #region 数据读取线程
    #endregion

    /// <summary>
    /// 下发工厂订单给Plc
    /// </summary>
    public class LineMesToPlc
    {
        public (S7.Net.Plc, string) OrderToPlc(OrderPlan orderPlan, string MaterialCode, string plcName)
        {
            try
            {
                bool isPut = false;

                // 遍历所有 PLC 配置并找到符合条件的 PLC 实例
                foreach (var plcConfig in PlcConnectionManager.plcContainer)
                {
                    if (plcName.Equals(plcConfig.name) && plcConfig.isConnected)
                    {

                        string orderNum = "";

                        //获取下发位置索引
                        int i = MappingTable.GetOrderCount(MaterialCode);

                        // 读取PLC中订单号的存储位置
                        byte[] bytes = plcConfig.plc.ReadBytes(DataType.DataBlock, SystemConstant.Order, i == 1 ? 0 : 772 * (i - 1), 256);
                        string isSaveOrderId = PlcDao.ParseS7String(bytes);

                        // 如果订单号为空，则写入订单信息
                        if (string.IsNullOrEmpty(isSaveOrderId))
                        {
                            plcConfig.plc.WriteBytes(DataType.DataBlock, SystemConstant.Order, i == 1 ? 0 : 772 * (i - 1), Tools.ConvertToPlcString(orderPlan.OrderId, orderPlan.OrderId.Length));
                            plcConfig.plc.WriteBytes(DataType.DataBlock, SystemConstant.Order, i == 1 ? 256 : 772 * ((i - 1)) + 256, Tools.ConvertToPlcString(MaterialCode, MaterialCode.Length));
                            plcConfig.plc.WriteBytes(DataType.DataBlock, SystemConstant.Order, i == 1 ? 512 : 772 * ((i - 1)) + 512, Tools.ConvertToPlcString(orderPlan.PartId, orderPlan.PartId.Length));
                            plcConfig.plc.Write(DataType.DataBlock, SystemConstant.Order, i == 1 ? 768 : 772 * ((i - 1)) + 768, short.Parse((Convert.ToInt16(orderPlan.ProduceNum)).ToString()));
                            if (!orderPlan.IsCheck)
                                plcConfig.plc.WriteBit(DataType.DataBlock, SystemConstant.Order, i == 1 ? 770 : (772 * (i - 1)) + 770, 0, true);
                            Tools.ProduceLogText($"订单已成功下发到PLC：{plcConfig.name}");
                            orderNum = i.ToString();
                            isPut = true;
                            return (plcConfig.plc, orderNum);
                        }
                        else
                        {
                            Tools.ProduceLogTextError($"订单下发失败：PLC {plcConfig.name} 已经包含该物料工单。");
                        }
                    }
                }
                if (!isPut)
                    Tools.ProduceLogTextError($"订单下发失败：未找到Plc实例，请检查连接状态。");
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"订单下发失败，原因是：{ex.Message}");
            }

            return (null, "");
        }
    }

}
